<template>
  <div class="container">
    <div style="font-size: 10px;float:right;color:white;">本次开启free模式，version api_key:{{ api_key }}</div>
    <t-chat
        ref="chatRef"
        layout="single"
        style="height: 600px"
        :clear-history="chatList.length > 0 && !isStreamLoad"
        @clear="clearConfirm"
    >
      <template v-for="(item, index) in chatList.slice().reverse()" :key="index">
        <t-chat-item
            :avatar="item.avatar"
            :name="item.name"
            :role="item.role"
            :datetime="item.datetime"
            :content="item.content"
            :text-loading="index === 0 && loading"
            variant="outline"
        >
          <template v-if="!isStreamLoad" #actions>
            <t-chat-action
                :is-good="isGood"
                :is-bad="isBad"
                :content="item.content"
                @operation="(type, { e }) => handleOperation(type, { e, index })"
            />
          </template>
        </t-chat-item>
      </template>
      <template #footer>
        <t-chat-input :stop-disabled="isStreamLoad" @send="inputEnter" @stop="onStop"> </t-chat-input>
      </template>
    </t-chat>
    <div style="margin:auto;padding-top:29px;text-align: center">
      <CloseCircleIcon size="36" style="margin:auto;text-align: center;color:white;cursor: pointer;" @click="onExit"/>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { backBottom } from './scroll.js';
import { ChatToAI, ShowApiKey } from '../../wailsjs/go/main/App.js';
import { createSSEConnection } from './fetchsse.js'; // 导入封装的 SSE 逻辑
import {
  Chat as TChat,
  ChatAction as TChatAction,
  ChatInput as TChatInput,
  ChatItem as TChatItem,
} from '@tdesign-vue-next/chat';
import {
  CloseCircleIcon,
} from 'tdesign-icons-vue-next';
import router from "../router/index.js";
const api_key = ref('');
const loading = ref(false);
const isStreamLoad = ref(false);
const isGood = ref(false);
const isBad = ref(false);
const chatRef = ref(null);
const chatList = ref([]);
const eventSource = ref(null); // 用于保存 EventSource 实例
const lastItem = ref(null); // 用于保存当前正在处理的 AI 消息

// 测试环境显示 apikey
onMounted(async () => {
  const data = await ShowApiKey();
  api_key.value = data.api_key;
  startSSEClient(); // 页面加载时初始化 SSE 连接
});

// 清空聊天记录
const clearConfirm = () => {
  chatList.value = [];
};

//退出
const onExit=()=>{
  if (eventSource.value) {
    eventSource.value.close(); // 关闭 SSE 连接
    eventSource.value = null;
  }
  loading.value = false;
  isStreamLoad.value = false;
  router.go(-1)
}
// 停止 SSE 连接
const onStop = () => {
  if (eventSource.value) {
    eventSource.value.close(); // 关闭 SSE 连接
    eventSource.value = null;
  }
  loading.value = false;
  isStreamLoad.value = false;
};

// 处理操作（点赞、点踩、重试）
const handleOperation = (type, options) => {
  const { index } = options;
  if (type === 'good') {
    isGood.value = !isGood.value;
    isBad.value = false;
  } else if (type === 'bad') {
    isBad.value = !isBad.value;
    isGood.value = false;
  } else if (type === 'replay') {
    const userQuery = chatList.value[index + 1].content;
    inputEnter(userQuery);
  }
};

// 处理用户输入
const inputEnter = (inputValue) => {
  if (isStreamLoad.value || !inputValue) return;

  // 添加用户消息
  chatList.value.push({
    avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
    name: '自己',
    datetime: new Date().toLocaleString(),
    content: inputValue,
    role: 'user',
  });

  // 添加空消息占位
  lastItem.value = {
    avatar: 'https://tdesign.gtimg.com/site/chat-avatar.png',
    name: 'DP✖️AI',
    datetime: new Date().toLocaleString(),
    content: '',
    role: 'assistant',
  };
  chatList.value.push(lastItem.value);

  // 发起 SSE 请求
  handleData(inputValue);
};

// 发起 SSE 请求
const handleData = async (inputValue) => {
  loading.value = true;
  isStreamLoad.value = true;
  try {
    await ChatToAI(inputValue); // 调用后端接口发送用户输入
  } catch (error) {
    isStreamLoad.value = false;
    loading.value = false;
    console.error('SSE request failed:', error);
  }
};

// 初始化 SSE 连接
const startSSEClient = () => {
  // 构建 SSE URL
  const url = new URL('http://localhost:8080/sse');
  let jsonData = {}
  // 创建 SSE 连接
  eventSource.value = createSSEConnection(
      url.toString(),
      (data) => {
        if (lastItem.value) {
          isStreamLoad.value = false;
          loading.value = false;
          lastItem.value.role = 'assistant';
          let jsonData = JSON.parse(data)
          lastItem.value.content += jsonData.choices[0]["delta"]["content"]; // 更新消息内容
          backBottom(chatRef.value); // 滚动到底部
        }
      },
      (error) => {
        if (lastItem.value) {
          lastItem.value.role = 'error';
          lastItem.value.content = '请求失败，请稍后重试';
        }
        console.error('SSE error:', error);
      },
      (isOk) => {
        isStreamLoad.value = false;
        loading.value = false;
        console.warn('关闭 loading');
      }
  );
};
</script>

<style scoped>
.container {
  background-image: linear-gradient(25deg, #3927a2, #7d56a7, #b088aa, #dfbdab);
  padding: 30px;
  box-sizing: border-box;
  min-height: 768px;
}
</style>